import os
import configparser
import pathlib
import types
from typing import Any

APP_PATH = pathlib.Path(os.path.realpath(__file__)).parent.parent
CONF_FILE_NAME = 'conf.ini'


def get_conf() -> configparser.ConfigParser:
    conf = configparser.ConfigParser()  # 类的实例化
    path = os.path.join(APP_PATH, CONF_FILE_NAME)
    conf.read(path, encoding="utf-8")
    conf.get_list = types.MethodType(_get_list, conf)
    conf.get_dict = types.MethodType(_get_list, conf)
    return conf


def _get_list(self, section, option):
    if self.has_option(section, option):
        return eval(self.get(section, option))


def write_conf_by_option(section, option, value: Any):
    conf = configparser.ConfigParser()  # 类的实例化
    path = os.path.join(APP_PATH, CONF_FILE_NAME)
    conf.read(path, encoding="utf-8")

    if not conf.has_section(section):
        conf.add_section(section)
    conf.set(section, option, str(value))

    with open(path, 'w', encoding='utf-8') as f:
        conf.write(f)  # 保存数据


def get_conf_device():
    conf = get_conf()
    device = conf.get('audio_setting', 'device')
    if device:
        return device


def _write_conf():
    conf = configparser.ConfigParser()  # 类的实例化
    path = os.path.join(APP_PATH, CONF_FILE_NAME)

    conf.add_section('size')  # 添加一个新的section
    conf.set('size', 'width', '1270')
    conf.set('size', 'height', '760')  # 往配置文件写入数据

    conf.add_section('path')
    conf.set('path', 'rootpath', 'C:\\')

    conf.add_section('audio_setting')
    conf.set('audio_setting', 'device', '')  # 音频输出

    conf.add_section('interact_track')
    conf.set('interact_track', 'panel_text_list', str(['款式互动', '回复模板', '后台回复']))
    conf.set('interact_track', 'default_new_title', '新建栏')
    conf.set('interact_track', 'panel_music_list_index0',
             str(['music_folder\\Beyond - 光辉岁月.mp3', 'music_folder\\G.E.M.邓紫棋 - 有心人.flac']))
    conf.set('interact_track', 'panel_music_list_index1',
             str(['music_folder\\单小源、本兮 - 你在看孤独的风景.mp3']))

    with open(path, 'w', encoding='utf-8') as f:
        conf.write(f)  # 保存数据


if __name__ == '__main__':
    _write_conf()
